//
//  Authentication.swift
//  HealthMonitoring
//
//  Created by 珠海正杰 on 2018/6/21.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

import UIKit
import Photos
import TZImagePickerController

class Authentication: HMViewController, HMPhotoDelegate, UIAlertViewDelegate{
 
    
    // MARK: - 变量
//    var certificateAry: [UIImageView]?
    
    var aSelectedPhotos = NSMutableArray()
    var aSelectedAssets = NSMutableArray()
    var aIsSelectOriginalPhoto: Bool = false
    ///
    var aCollectionView: UICollectionView?
    ///
    var aLayout: UICollectionViewFlowLayout?
    var aMargin: CGFloat = 0.0
    var aItemWH: CGFloat = 0.0
    /// 保存医院名称列表
    var doctorList   = Array<Any>()
    
    
    //MARK: -常量
    let nickname: UILabel = UILabel()
    let department  = UILabel()
    let _title  = UILabel()
    let nicknameField = UITextField()
    let departmentField = UITextField()
    let _titleField = UITextField()
    
    let headImg = UIImageView() //头像
    let place = UILabel() //地点
    let hospital =  UIButton() //UITextField()
    let describe = UILabel()
    let identification = UIImageView()
    let identificationDescribe = UILabel()
    let certificateDescribe = UILabel()
    

    let checkButton = UIButton()
    let clauseButton = UIButton()
    let determine = UIButton()
    let complete = UIButton()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        HMPhoto.shareInstance.delegate = self
    }
    
    override func setupView() {
        self.title = "医生认证"
        view.backgroundColor = UIColor.white
        view.addSubview(headImg)
        view.addSubview(nickname)
        view.addSubview(department)
        view.addSubview(_title)
        view.addSubview(nicknameField)
        view.addSubview(departmentField)
        view.addSubview(_titleField)
        view.addSubview(place)
        view.addSubview(hospital)
        view.addSubview(describe)
        view.addSubview(identificationDescribe)
        view.addSubview(identification)
        view.addSubview(certificateDescribe)
        view.addSubview(checkButton)
        view.addSubview(clauseButton)
        view.addSubview(determine)
        view.addSubview(complete)
        
        
        headImg.topAlign(view: view)
        headImg.leadingAlign(view: view, predicate: "30")
        headImg.widthConstrain(predicate: "100")
        headImg.heightConstrain(predicate: "100")
        headImg.imgName(name: "logo.png")
        headImg.layer.cornerRadius = 30
        
        headImg.addTapGesture(target: self, action: #selector(headImgClick))

        
        nickname.leadingHorizontally(view: headImg, predicate: "80")
        nickname.topAlign(view: view, predicate: "20")
        nickname.text = "昵称"
        
        department.leadingHorizontally(view: headImg, predicate: "80")
        department.topVertically(view: nickname, predicate: "10")
        department.text = "科室"
        
        _title.topVertically(view: department, predicate: "10")
        _title.leadingHorizontally(view: headImg, predicate:  "80")
        _title.text = "职称"
        
        
        nicknameField.leadingHorizontally(view: nickname, predicate: "10")
        nicknameField.centerYAlign(view: nickname)
        nicknameField.widthConstrain(predicate: "130")
        nicknameField.trailingAlign(view: view, predicate: "-20")
        nicknameField.placeholder = "请输入昵称"
        nicknameField.addLayer(isAddLayer: (false, false, false, true), color: UIColor.gray, crude: 2, layout: (w: 130, h: 26))
        
        
        departmentField.leadingHorizontally(view: department, predicate: "10")
        departmentField.centerYAlign(view: department)
        departmentField.widthConstrain(predicate: "130")
        departmentField.trailingAlign(view: view, predicate: "-20")
        departmentField.placeholder = "请输入科室"
        departmentField.addLayer(isAddLayer: (false, false, false, true), color: UIColor.gray, crude: 2, layout: (w: 130, h: 26))
        
        
        _titleField.leadingHorizontally(view: _title, predicate: "10")
        _titleField.centerYAlign(view: _title)
        _titleField.widthConstrain(predicate: "130")
        _titleField.trailingAlign(view: view, predicate: "-20")
        _titleField.placeholder = "请输入职称"
        _titleField.addLayer(isAddLayer: (false, false, false, true), color: UIColor.gray, crude: 2, layout: (w: 130, h: 26))
        
        
        
        place.topVertically(view: headImg, predicate: "20")
        place.leadingAlign(view: view, predicate: "20")
        place.trailingAlign(view: view, predicate: "-20")
        place.text = "工作地点"
        
        hospital.topVertically(view: place, predicate: "10")
        hospital.leadingAlign(view: view, predicate: "20")
        hospital.widthConstrain(predicate: "200")
        hospital.heightConstrain(predicate: "44")
//        hospital.placeholder = "请输入医院名称"
        hospital.setTitle("请输入医院名称", for: .normal)
        hospital.setTitleColor(UIColor.gray, for: .normal)
        hospital.addTarget(self, action: #selector(hospitalClick), for: UIControlEvents.touchUpInside)
        let hospitalLayer = CALayer()
        hospitalLayer.frame = CGRect.init(x: 0, y: 44, width: 200, height: 2)
        hospitalLayer.backgroundColor = UIColor.gray.cgColor
        hospital.layer.addSublayer(hospitalLayer)
        
        describe.topVertically(view: hospital, predicate: "10")
        describe.leadingAlign(view: view, predicate: "20")
        describe.trailingAlign(view: view, predicate: "-20")
        describe.font = UIFont.systemFont(ofSize: 14)
        describe.textColor = UIColor.gray
//        describe.backgroundColor = UIColor.red
        describe.text = "注意：以下只做认证，不公开"
        
        identificationDescribe.topVertically(view: describe, predicate: "20")
        identificationDescribe.leadingAlign(view: view, predicate: "20")
        identificationDescribe.trailingAlign(view: view, predicate: "-20")
        identificationDescribe.text = "身份证正面照片"
        
        identification.topVertically(view: identificationDescribe, predicate: "20")
        identification.leadingAlign(view: view, predicate: "20")
        identification.imgName(name: "sfz.png")
        identification.widthConstrain(predicate: "180")
        identification.heightConstrain(predicate: "100")
        identification.backgroundColor = configure.shareConfigure.HMColor3
        identification.addTapGesture(target:self, action: #selector(identificationClick)) //添加方法
        
        
        certificateDescribe.topVertically(view: identification, predicate: "20")
        certificateDescribe.leadingAlign(view: view, predicate: "20")
        certificateDescribe.text = "医生执业证书"
        
        
        aCollectionView = configCollectionView()
        view.addSubview(aCollectionView!)
        aCollectionView?.topVertically(view: certificateDescribe, predicate: "10")
        aCollectionView?.heightConstrain(predicate: "130")
        aCollectionView?.leadingAlign(view: view)
        aCollectionView?.trailingAlign(view: view)
        
        
        checkButton.topVertically(view: aCollectionView!, predicate: "10")
        checkButton.centerXAlign(view: view, predicate: "-50")
        checkButton.setImage(UIImage(named:"check_false.png"), for: .normal)
        checkButton.setTitleColor(UIColor.black, for: .normal)
        checkButton.setTitle(" 我同意 ", for: .normal)
        checkButton.setImage(UIImage(named:"check_true.png"), for: .selected)
        checkButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        checkButton.heightConstrain(predicate: "25")

        let mutStr: NSMutableAttributedString = NSMutableAttributedString(string: "《乐众康使用手册》")
        mutStr.addAttribute(NSAttributedStringKey.foregroundColor as NSAttributedStringKey , value: configure.shareConfigure.HMColor1, range: NSRange.init(location: 0, length: mutStr.length))
        //        mutStr.addAttribute(NSAttributedStringKey.underlineStyle, value: 1, range: NSRange.init(location: 0, length:1))

        clauseButton.topVertically(view: aCollectionView!, predicate: "10")
        clauseButton.leadingAlign(view: checkButton, predicate: "55")
        clauseButton.setTitleColor(UIColor.blue, for: .normal)
        clauseButton.setAttributedTitle(mutStr, for: .normal)
        clauseButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
//        clauseButton.addTarget(self, action: #selector(regulationsClick), for: .touchUpInside)
        clauseButton.heightConstrain(predicate: "25")


        complete.topVertically(view: clauseButton, predicate: "10")
        complete.leadingAlign(view: view, predicate: "60")
        complete.trailingAlign(view: view, predicate: "-60")
        complete.backgroundColor =   configure.shareConfigure.HMColor1
        complete.heightConstrain(predicate: "44")
        complete.setTitle("完成注册", for: .normal)
        complete.setTitleColor(UIColor.white, for: .normal)
//        complete.addTarget(self, action: #selector(completeClick), for: .touchUpInside)
        complete.layer.borderColor =  configure.shareConfigure.HMColor1.cgColor
        complete.layer.borderWidth = 2
        complete.layer.cornerRadius = 20
            }
    
    @objc func identificationClick(sender: UITapGestureRecognizer)  {
          HMPhoto.shareInstance.pushTZImagePickerController(self, max: 1, column: 3, isSelectOriginal: false)
          HMPhoto.shareInstance.hmImagePickerVc?.didFinishPickingPhotosHandle = {
            (photos: [UIImage]!, assets: [Any]!, isSelectOriginalPhoto: Bool) -> () in
             self.identification.image = photos[0]
        }
    }
    @objc func headImgClick(sender: UITapGestureRecognizer)  {
         // 医生头像
        HMPhoto.shareInstance.pushTZImagePickerController(self, max: 1, column: 3, isSelectOriginal: false)
        HMPhoto.shareInstance.hmImagePickerVc?.didFinishPickingPhotosHandle = {
            (photos: [UIImage]!, assets: [Any]!, isSelectOriginalPhoto: Bool) -> () in
            self.headImg.image = photos[0]
        }
    }
    @objc func hospitalClick(sender: UIButton) {
        NetRequestTool.shareInstance.met = .get
        NetRequestTool.request(url: "doctor/hospital-config", parameters: [:], success: { (json) in
            
            self.doctorList = json["data"].arrayObject!    //as Array<String>
            var ary1 = Array<String>()
            for item in  json["data"].arrayValue {
                ary1.append(item["hospitalName"].stringValue)
            }
            HMPickerView.sharePicker.delegate = self
            HMPickerView.creator(nil, picker: ["Ary" : ary1])
            
        }, fail: { (code, msg) in
            print("----->code: \(code), msg: \(msg)")
        }) {}
    }
    
}

extension Authentication: UICollectionViewDelegate, UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if aSelectedPhotos.count >= HMPhoto.shareInstance.maxCount {
           return aSelectedPhotos.count
        }
        
        return  aSelectedPhotos.count + 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TZTestCell", for: indexPath) as! TZTestCell
        cell.videoImageView.isHidden = true
        
        if indexPath.item == aSelectedPhotos.count {
            cell.imageView.image = UIImage.init(named: "yszs.png")
            //            cell.imageView.isUserInteractionEnabled = true
            cell.deleteBtn.isHidden = true
            cell.gifLable.isHidden = true
        }else {
            cell.imageView.image = aSelectedPhotos[indexPath.item] as? UIImage
            cell.asset = aSelectedAssets[indexPath.item]
            cell.deleteBtn.isHidden = false
        }
        //显示动态
        cell.gifLable.isHidden = true
        cell.deleteBtn.tag = indexPath.item
        cell.deleteBtn.addTarget(self, action: #selector(deleteBtnClick), for: UIControlEvents.touchUpInside)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.item == aSelectedPhotos.count {
            let tabkePhotoTitle = "拍照"
            
            let alertVc = UIAlertController.init(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
            let takePhotoAction = UIAlertAction.init(title: tabkePhotoTitle, style: UIAlertActionStyle.default) { (action) in
                // 事件
                  print("拍照")
                  HMPhoto.shareInstance.takePhoto(self)
            }
            alertVc.addAction(takePhotoAction)
            
            let imagePickerAction = UIAlertAction.init(title: "去相册选择", style: .default) { (imgAction) in
                // 事件
                print("去相册选择")
                 HMPhoto.shareInstance.isOpenStorage = true
                 HMPhoto.shareInstance.pushTZImagePickerController(self, max: 3, column: 9, isSelectOriginal: true)
                  /// 你可以通过block或者代理，来得到用户选择的照片.
                 HMPhoto.shareInstance.hmImagePickerVc!.didFinishPickingPhotosHandle = {
                            (photos: [UIImage]!, assets: [Any]!, isSelectOriginalPhoto: Bool) -> () in
                            self.aSelectedPhotos = NSMutableArray.init(array: photos)
                            self.aSelectedAssets = NSMutableArray.init(array: assets)
                            self.aIsSelectOriginalPhoto = isSelectOriginalPhoto
                            self.aCollectionView?.reloadData()
                 }
                
            }
            alertVc.addAction(imagePickerAction)
            
            let canceAction = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
            
            alertVc.addAction(canceAction)
            // --- ---- 位置
//            let popover : UIPopoverPresentationController  = alertVc.popoverPresentationController!
//            let cell : UICollectionViewCell = collectionView.cellForItem(at: indexPath)!
//            if popover != nil {
//                popover.sourceView = cell
//                popover.sourceRect = cell.bounds
//                popover.permittedArrowDirections = UIPopoverArrowDirection.any
//            }
             self.present(alertVc, animated: true, completion: nil)
            
        }else { // preview photos or video / 预览照片或者视频

            print("预览部分照片")
//            let asset: PHAsset = aSelectedAssets[indexPath.item] as! PHAsset

            let imagePickerVc: TZImagePickerController = TZImagePickerController.init(selectedAssets: aSelectedAssets, selectedPhotos: aSelectedPhotos, index: indexPath.item)
            imagePickerVc.maxImagesCount = HMPhoto.shareInstance.maxCount
            imagePickerVc.allowPickingGif = false
            imagePickerVc.allowPickingOriginalPhoto = true
            imagePickerVc.allowPickingMultipleVideo = false
            imagePickerVc.showSelectedIndex = true
            imagePickerVc.isSelectOriginalPhoto = HMPhoto.shareInstance.isSelectOriginalPhoto
            imagePickerVc.didFinishPickingPhotosHandle = {
                (photos, assets, isSelectOriginalPhoto) -> () in
                //回调
                self.aSelectedPhotos  = NSMutableArray.init(array: photos!)
                self.aSelectedAssets = NSMutableArray.init(array: assets!)
                self.aIsSelectOriginalPhoto = isSelectOriginalPhoto
                self.aCollectionView?.reloadData()
                self.aCollectionView?.contentSize = CGSize.init(width: 0, height: ((CGFloat(self.aSelectedPhotos.count) + 2.0) / 3.0) * (self.aMargin + self.aItemWH))
            }
            self.present(imagePickerVc, animated: true, completion: nil)
            
        }
    }
    
    /**
     * 删除按钮事件 -有问题
     */
    @objc func deleteBtnClick(sender: UIButton) {
//        if self.collectionView(aCollectionView!, numberOfItemsInSection: 0) <= aSelectedPhotos.count {
//            aSelectedPhotos.remove(sender.tag)
//            aSelectedAssets.remove(sender.tag)
//            aCollectionView?.reloadData()
//            return
//        }
//        aSelectedPhotos.remove(sender.tag)
//        aSelectedAssets.remove(sender.tag)
//
//        aCollectionView?.performBatchUpdates({
//            let indexPath = NSIndexPath.init(item: sender.tag, section: 0)
//            self.aCollectionView?.deleteItems(at: [indexPath as IndexPath])
//        }, completion: { (finished) in
//            self.aCollectionView?.reloadData()
//        })
        
    }
    
   private func configCollectionView() -> UICollectionView{
        aLayout = UICollectionViewFlowLayout()
        let coll = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: aLayout!)
        coll.backgroundColor = UIColor.clear
        coll.alwaysBounceVertical = true
        coll.contentInset = UIEdgeInsetsMake(4, 4, 4, 4)
        coll.register(TZTestCell.classForCoder(), forCellWithReuseIdentifier: "TZTestCell")
        coll.dataSource = self
        coll.delegate = self
    
        aMargin =  4.0
        aItemWH = (configure.shareConfigure.screenWidth - 16.0 - 2.0 * aMargin - 4.0) / 3 - aMargin
        aLayout?.itemSize = CGSize.init(width: aItemWH, height: aItemWH)
        aLayout?.minimumInteritemSpacing = aMargin
        aLayout?.minimumLineSpacing = aMargin
        coll.setCollectionViewLayout(aLayout!, animated: true)
        let collectionViewY :  CGFloat = 0
        coll.frame =  CGRect.init(x: 0, y: collectionViewY, width: configure.shareConfigure.screenWidth, height: 130)
    
        return coll
    }
    
    
    
}

// HMPickerViewDelegate
extension Authentication: HMPickerViewDelegate {
    func cancel() {
    }
    func selectValue(value: String, row: Int, component: Int) {
        //一个cell刷新
//        let indexPath = self.selectIndexPath!
//        let newcell = self.tableView.cellForRow(at: indexPath) as! OptionCell
//        newcell.describe.text = value
    }
    
}
